import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import '../services/api_service.dart';
import '../utils/logger.dart';

/// 高级富文本编辑器
/// 支持HTML格式的富文本编辑，包括文本格式化、图片插入等功能
class AdvancedRichTextEditor extends StatefulWidget {
  final String? initialContent;
  final String hintText;
  final Function(String htmlContent)? onContentChanged;
  final Function(String htmlContent)? onSubmit;
  final bool enabled;
  final double? minHeight;
  final bool showToolbar;

  const AdvancedRichTextEditor({
    super.key,
    this.initialContent,
    this.hintText = '请输入文章内容...',
    this.onContentChanged,
    this.onSubmit,
    this.enabled = true,
    this.minHeight = 300,
    this.showToolbar = true,
  });

  @override
  State<AdvancedRichTextEditor> createState() => _AdvancedRichTextEditorState();
}

class _AdvancedRichTextEditorState extends State<AdvancedRichTextEditor> {
  late TextEditingController _controller;
  final FocusNode _focusNode = FocusNode();
  final ApiService _apiService = ApiService();
  final ImagePicker _picker = ImagePicker();
  
  bool _isUploading = false;
  bool _isBold = false;
  bool _isItalic = false;
  bool _isUnderline = false;
  
  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
    if (widget.initialContent != null) {
      _controller.text = _stripHtmlTags(widget.initialContent!);
    }
    _controller.addListener(_onTextChanged);
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  void _onTextChanged() {
    if (widget.onContentChanged != null) {
      widget.onContentChanged!(_generateHtml());
    }
  }

  /// 生成HTML内容（完整的Markdown到HTML转换）
  String _generateHtml() {
    String text = _controller.text;
    if (text.isEmpty) return '';
    
    // 按行处理
    List<String> lines = text.split('\n');
    List<String> htmlLines = [];
    bool inList = false;
    bool isOrderedList = false;
    
    for (int i = 0; i < lines.length; i++) {
      String line = lines[i];
      
      // 处理标题 (# ## ###)
      if (line.startsWith('### ')) {
        if (inList) {
          htmlLines.add(isOrderedList ? '</ol>' : '</ul>');
          inList = false;
        }
        String content = _processInlineFormatting(line.substring(4));
        htmlLines.add('<h3>$content</h3>');
        continue;
      } else if (line.startsWith('## ')) {
        if (inList) {
          htmlLines.add(isOrderedList ? '</ol>' : '</ul>');
          inList = false;
        }
        String content = _processInlineFormatting(line.substring(3));
        htmlLines.add('<h2>$content</h2>');
        continue;
      } else if (line.startsWith('# ')) {
        if (inList) {
          htmlLines.add(isOrderedList ? '</ol>' : '</ul>');
          inList = false;
        }
        String content = _processInlineFormatting(line.substring(2));
        htmlLines.add('<h1>$content</h1>');
        continue;
      }
      
      // 处理引用 (> )
      if (line.startsWith('> ')) {
        if (inList) {
          htmlLines.add(isOrderedList ? '</ol>' : '</ul>');
          inList = false;
        }
        String content = _processInlineFormatting(line.substring(2));
        htmlLines.add('<blockquote>$content</blockquote>');
        continue;
      }
      
      // 处理无序列表 (- )
      if (line.startsWith('- ')) {
        if (!inList || isOrderedList) {
          if (inList) htmlLines.add('</ol>');
          htmlLines.add('<ul>');
          inList = true;
          isOrderedList = false;
        }
        String content = _processInlineFormatting(line.substring(2));
        htmlLines.add('<li>$content</li>');
        continue;
      }
      
      // 处理有序列表 (1. 2. 等)
      RegExp orderedListRegex = RegExp(r'^(\d+)\.\s');
      Match? orderedMatch = orderedListRegex.firstMatch(line);
      if (orderedMatch != null) {
        if (!inList || !isOrderedList) {
          if (inList) htmlLines.add('</ul>');
          htmlLines.add('<ol>');
          inList = true;
          isOrderedList = true;
        }
        String content = _processInlineFormatting(line.substring(orderedMatch.end));
        htmlLines.add('<li>$content</li>');
        continue;
      }
      
      // 关闭列表（如果当前行不是列表项）
      if (inList && line.trim().isNotEmpty) {
        htmlLines.add(isOrderedList ? '</ol>' : '</ul>');
        inList = false;
      }
      
      // 处理空行
      if (line.trim().isEmpty) {
        if (inList) {
          htmlLines.add(isOrderedList ? '</ol>' : '</ul>');
          inList = false;
        }
        continue;
      }
      
      // 普通段落
      String content = _processInlineFormatting(line);
      htmlLines.add('<p>$content</p>');
    }
    
    // 关闭未关闭的列表
    if (inList) {
      htmlLines.add(isOrderedList ? '</ol>' : '</ul>');
    }
    
    return htmlLines.join('\n');
  }
  
  /// 处理行内格式（粗体、斜体、下划线、图片、链接）
  String _processInlineFormatting(String text) {
    String result = text;
    
    // 处理图片 ![alt](url)
    result = result.replaceAllMapped(
      RegExp(r'!\[([^\]]*)\]\(([^)]+)\)'),
      (match) => '<img src="${match.group(2)}" alt="${match.group(1)}" style="max-width:100%;height:auto;"/>',
    );
    
    // 处理链接 [text](url)
    result = result.replaceAllMapped(
      RegExp(r'\[([^\]]+)\]\(([^)]+)\)'),
      (match) => '<a href="${match.group(2)}">${match.group(1)}</a>',
    );
    
    // 处理粗体 **text** 或 __text__
    result = result.replaceAllMapped(
      RegExp(r'\*\*([^*]+)\*\*'),
      (match) => '<strong>${match.group(1)}</strong>',
    );
    result = result.replaceAllMapped(
      RegExp(r'__([^_]+)__'),
      (match) => '<strong>${match.group(1)}</strong>',
    );
    
    // 处理斜体 *text* 或 _text_
    result = result.replaceAllMapped(
      RegExp(r'\*([^*]+)\*'),
      (match) => '<em>${match.group(1)}</em>',
    );
    result = result.replaceAllMapped(
      RegExp(r'_([^_]+)_'),
      (match) => '<em>${match.group(1)}</em>',
    );
    
    // 处理行内代码 `code`
    result = result.replaceAllMapped(
      RegExp(r'`([^`]+)`'),
      (match) => '<code>${match.group(1)}</code>',
    );
    
    // 下划线标签保持不变（已经是HTML格式）
    
    return result;
  }

  /// 移除HTML标签
  String _stripHtmlTags(String htmlString) {
    final RegExp exp = RegExp(r"<[^>]*>", multiLine: true, caseSensitive: true);
    return htmlString.replaceAll(exp, '').replaceAll('<br>', '\n').trim();
  }

  /// 插入格式化文本
  void _insertFormatting(String startTag, String endTag, {String? placeholder}) {
    final selection = _controller.selection;
    final text = _controller.text;
    
    String selectedText = '';
    if (selection.start != selection.end) {
      selectedText = text.substring(selection.start, selection.end);
    } else if (placeholder != null) {
      selectedText = placeholder;
    }
    
    final newText = text.replaceRange(
      selection.start,
      selection.end,
      '$startTag$selectedText$endTag',
    );
    
    _controller.text = newText;
    
    // 设置新的光标位置
    int newOffset;
    if (selectedText.isEmpty && placeholder != null) {
      newOffset = selection.start + startTag.length;
    } else {
      newOffset = selection.start + startTag.length + selectedText.length + endTag.length;
    }
    
    _controller.selection = TextSelection.collapsed(offset: newOffset);
    _focusNode.requestFocus();
  }

  /// 插入标题
  void _insertHeading(int level) {
    final selection = _controller.selection;
    final text = _controller.text;
    
    // 找到当前行的开始
    int lineStart = selection.start;
    while (lineStart > 0 && text[lineStart - 1] != '\n') {
      lineStart--;
    }
    
    // 找到当前行的结束
    int lineEnd = selection.start;
    while (lineEnd < text.length && text[lineEnd] != '\n') {
      lineEnd++;
    }
    
    String currentLine = text.substring(lineStart, lineEnd);
    String prefix = '#' * level + ' ';
    
    // 如果已经是标题，则移除标题格式
    if (currentLine.startsWith('#')) {
      final RegExp headingRegex = RegExp(r'^#+\s*');
      currentLine = currentLine.replaceFirst(headingRegex, '');
    }
    
    String newLine = prefix + currentLine;
    
    final newText = text.replaceRange(lineStart, lineEnd, newLine);
    _controller.text = newText;
    
    final newOffset = lineStart + newLine.length;
    _controller.selection = TextSelection.collapsed(offset: newOffset);
    _focusNode.requestFocus();
  }

  /// 插入列表
  void _insertList(bool isOrdered) {
    final selection = _controller.selection;
    final text = _controller.text;
    
    String prefix = isOrdered ? '1. ' : '- ';
    String placeholder = '列表项';
    
    final newText = text.replaceRange(
      selection.start,
      selection.end,
      '\n$prefix$placeholder\n',
    );
    
    _controller.text = newText;
    
    final newOffset = selection.start + 1 + prefix.length;
    _controller.selection = TextSelection(
      baseOffset: newOffset,
      extentOffset: newOffset + placeholder.length,
    );
    _focusNode.requestFocus();
  }

  /// 插入引用
  void _insertQuote() {
    final selection = _controller.selection;
    final text = _controller.text;
    
    String quote = '\n> 引用内容\n';
    
    final newText = text.replaceRange(selection.start, selection.end, quote);
    _controller.text = newText;
    
    final newOffset = selection.start + 3;
    _controller.selection = TextSelection(
      baseOffset: newOffset,
      extentOffset: newOffset + 4,
    );
    _focusNode.requestFocus();
  }

  /// 插入图片
  Future<void> _insertImage() async {
    if (_isUploading) return;
    
    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1920,
        maxHeight: 1080,
        imageQuality: 85,
      );
      
      if (image == null) return;
      
      setState(() {
        _isUploading = true;
      });
      
      // 上传图片
      final result = await _apiService.uploadPostImage(
        File(image.path),
      );
      
      if (result['code'] == 200 || result['code'] == 0) {
        final imageUrl = result['data'] as String;
        
        // 插入图片标记
        final selection = _controller.selection;
        final text = _controller.text;
        
        String imageMarkdown = '\n![图片]($imageUrl)\n';
        
        final newText = text.replaceRange(
          selection.start,
          selection.end,
          imageMarkdown,
        );
        
        _controller.text = newText;
        
        final newOffset = selection.start + imageMarkdown.length;
        _controller.selection = TextSelection.collapsed(offset: newOffset);
        _focusNode.requestFocus();
        
        Logger.d('RICH_TEXT_EDITOR', '图片插入成功: $imageUrl');
      } else {
        _showError('图片上传失败：${result['message']}');
      }
    } catch (e) {
      Logger.e('RICH_TEXT_EDITOR', '插入图片失败: $e');
      _showError('插入图片失败：$e');
    } finally {
      setState(() {
        _isUploading = false;
      });
    }
  }

  /// 显示错误信息
  void _showError(String message) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 构建工具栏
  Widget _buildToolbar() {
    if (!widget.showToolbar) return const SizedBox.shrink();
    
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
      ),
      child: Wrap(
        spacing: 4,
        children: [
          // 标题
          _buildToolbarButton(
            icon: Icons.title,
            label: 'H1',
            onPressed: () => _insertHeading(1),
          ),
          _buildToolbarButton(
            icon: Icons.title,
            label: 'H2',
            onPressed: () => _insertHeading(2),
          ),
          _buildToolbarButton(
            icon: Icons.title,
            label: 'H3',
            onPressed: () => _insertHeading(3),
          ),
          
          const SizedBox(width: 8),
          
          // 格式化
          _buildToolbarButton(
            icon: Icons.format_bold,
            isActive: _isBold,
            onPressed: () {
              _insertFormatting('**', '**', placeholder: '粗体文字');
              setState(() {
                _isBold = !_isBold;
              });
            },
          ),
          _buildToolbarButton(
            icon: Icons.format_italic,
            isActive: _isItalic,
            onPressed: () {
              _insertFormatting('*', '*', placeholder: '斜体文字');
              setState(() {
                _isItalic = !_isItalic;
              });
            },
          ),
          _buildToolbarButton(
            icon: Icons.format_underlined,
            isActive: _isUnderline,
            onPressed: () {
              _insertFormatting('<u>', '</u>', placeholder: '下划线文字');
              setState(() {
                _isUnderline = !_isUnderline;
              });
            },
          ),
          
          const SizedBox(width: 8),
          
          // 列表和引用
          _buildToolbarButton(
            icon: Icons.format_list_bulleted,
            onPressed: () => _insertList(false),
          ),
          _buildToolbarButton(
            icon: Icons.format_list_numbered,
            onPressed: () => _insertList(true),
          ),
          _buildToolbarButton(
            icon: Icons.format_quote,
            onPressed: _insertQuote,
          ),
          
          const SizedBox(width: 8),
          
          // 图片
          _buildToolbarButton(
            icon: Icons.image,
            onPressed: _isUploading ? null : _insertImage,
            child: _isUploading 
              ? const SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(strokeWidth: 2),
                )
              : null,
          ),
        ],
      ),
    );
  }

  /// 构建工具栏按钮
  Widget _buildToolbarButton({
    required IconData icon,
    String? label,
    bool isActive = false,
    VoidCallback? onPressed,
    Widget? child,
  }) {
    return InkWell(
      onTap: onPressed,
      borderRadius: BorderRadius.circular(4),
      child: Container(
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          color: isActive ? Colors.blue[100] : null,
          borderRadius: BorderRadius.circular(4),
        ),
        child: child ?? Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              icon,
              size: 18,
              color: isActive ? Colors.blue : Colors.grey[700],
            ),
            if (label != null) ...[
              const SizedBox(width: 4),
              Text(
                label,
                style: TextStyle(
                  fontSize: 12,
                  color: isActive ? Colors.blue : Colors.grey[700],
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[300]!),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          _buildToolbar(),
          Expanded(
            child: TextField(
              controller: _controller,
              focusNode: _focusNode,
              enabled: widget.enabled,
              maxLines: null,
              expands: true,
              textAlignVertical: TextAlignVertical.top,
              decoration: InputDecoration(
                hintText: widget.hintText,
                border: InputBorder.none,
                contentPadding: const EdgeInsets.all(16),
                hintStyle: TextStyle(color: Colors.grey[400]),
              ),
              style: const TextStyle(
                fontSize: 16,
                height: 1.5,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
